package site.xuqing.nobean;

import site.xuqing.nobean.analysis.AnalysisJson;
import site.xuqing.nobean.obj.INonObject;
import site.xuqing.nobean.obj.NonObject;

/**
 * @author xuqing
 * @Description NoBean
 * @createTime 2022年01月20日 10:13:34
 */
public class NoBean {
    private NonObject mNonObject;
    private final AnalysisJson mAnalysisJson;
    
    private static class NoBeanHolder {
        private static final NoBean INSTANCE = new NoBean();
    }
    
    private NoBean() {
        mAnalysisJson = new AnalysisJson();
    }
    
    /**
     * 获取实例
     *
     * @return NoBean
     */
    public static NoBean getInstance() {
        return NoBeanHolder.INSTANCE;
    }
    
    /**
     * 设置目标json
     *
     * @param json 需要解析的json
     * @return NoBean
     */
    public NoBean setJson(String json) {
        mNonObject = mAnalysisJson.analysisFromJson(json);
        return this;
    }
    
    /**
     * 获取解析后的NonObject对象
     *
     * @return NonObject对象
     */
    public <T extends INonObject> T getBean() {
        if (mNonObject == null) {
            throw new RuntimeException("the setJson() method must be called first!");
        }
        return (T) mNonObject;
    }
    
    /**
     * 对象INonObject 解析成 json
     *
     * @param object object
     * @return json
     */
    public static String toJson(INonObject object) {
        return new AnalysisJson().analysisToJson(object);
    }
    
    /**
     * 获取解析后的NonObject对象
     *
     * @param json 需要解析的json
     * @return NonObject对象
     */
    public static <T extends INonObject> T formJson(String json) {
        return new AnalysisJson().analysisFromJson(json);
    }
    
    /**
     * 手动清除NonObject内存
     *
     * @param object NonObject
     */
    public static void clear(INonObject object) {
        object.clear();
    }
}
